package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.base.exception.RestErrorResponse;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * @Author: 40斤
 * @CreateTime: 2024-07-29  17:06
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class TeachplanServiceImpl implements TeachplanService {
    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;
    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    @Transactional
    @Override
    public void saveTeachplan(SaveTeachplanDto teachplanDto) {

        //课程计划id
        Long id = teachplanDto.getId();
        //修改课程计划 修改前端传输id 新增则id为空
        if(id!=null){
            Teachplan teachplan = teachplanMapper.selectById(id);
            BeanUtils.copyProperties(teachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }else{
            //取出同父同级别的课程计划数量
            int count = getTeachplanCount(teachplanDto.getCourseId(), teachplanDto.getParentid());
            Teachplan teachplanNew = new Teachplan();
            //设置排序号
            BeanUtils.copyProperties(teachplanDto,teachplanNew);
            teachplanNew.setOrderby(count+1);
            teachplanMapper.insert(teachplanNew);
        }

    }

    @Override
    public void deleteTeachplan(Long courseId) {
        //判断是否是大章节
        Teachplan teachplan = teachplanMapper.selectById(courseId);
        if(teachplan.getGrade()==1){
            //大章节 有小章节直接返回错误
            QueryWrapper<Teachplan> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("parentid",courseId);
            if (teachplanMapper.selectCount(queryWrapper)>0) {
                XueChengPlusException.cast("该课程计划下有子课程计划，无法删除");
            }
            //没有小删除大章节
            teachplanMapper.deleteById(courseId);
        }else {
            //删除小章节
            teachplanMapper.deleteById(courseId);
            //删除与视频关联的中间表
            teachplanMapper.deleteMedia(teachplan.getId());
        }
    }

    @Override
    public void updateOrderTeachplan(String moveType, Long teachplanId) {
        if ("moveup".equals(moveType)){
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            if (teachplan.getOrderby()==1){
                XueChengPlusException.cast("已经是第一个了，不能再上移了");
            }
            //获取上一个课程
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getOrderby,teachplan.getOrderby()-1)
                    .eq(Teachplan::getParentid,teachplan.getParentid())
                    .eq(Teachplan::getCourseId,teachplan.getCourseId());
            Teachplan preTeachplan = teachplanMapper.selectOne(queryWrapper);
            //修改两个课程的排序号
            preTeachplan.setOrderby(teachplan.getOrderby());
            teachplan.setOrderby(teachplan.getOrderby()-1);
            teachplanMapper.updateById(preTeachplan);
            teachplanMapper.updateById(teachplan);
        }
        if ("movedown".equals(moveType)){
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            if (teachplan.getOrderby()==getTeachplanCount(teachplan.getCourseId(),teachplan.getParentid())){
                XueChengPlusException.cast("已经是最后一个了，不能再下移了");
            }
            //获取下一个课程
            LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getOrderby,teachplan.getOrderby()+1)
                    .eq(Teachplan::getParentid,teachplan.getParentid())
                    .eq(Teachplan::getCourseId,teachplan.getCourseId());
            Teachplan nextTeachplan = teachplanMapper.selectOne(queryWrapper);
            //修改两个课程的排序号
            nextTeachplan.setOrderby(teachplan.getOrderby());
            teachplan.setOrderby(teachplan.getOrderby()+1);
            teachplanMapper.updateById(nextTeachplan);
            teachplanMapper.updateById(teachplan);
        }
    }


    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        //教学计划id
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if(teachplan==null){
            XueChengPlusException.cast("教学计划不存在");
        }
        Integer grade = teachplan.getGrade();
        if(grade!=2){
            XueChengPlusException.cast("只允许第二级教学计划绑定媒资文件");
        }
        //课程id
        Long courseId = teachplan.getCourseId();

        //先删除原来该教学计划绑定的媒资
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>().eq(TeachplanMedia::getTeachplanId,teachplanId));

        //再添加教学计划与媒资的绑定关系
        TeachplanMedia teachplanMedia = new TeachplanMedia();
        teachplanMedia.setCourseId(courseId);
        teachplanMedia.setTeachplanId(teachplanId);
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }



    /**
     * @description 获取最新的排序号
     * @param courseId  课程id
     * @param parentId  父课程计划id
     * @return int 最新排序号
     * @author Mr.M
     * @date 2022/9/9 13:43
     */
    private int getTeachplanCount(long courseId,long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count;
    }
}
